﻿using AutoMapper;
using B.S.Warehouse.Domain;
using B.S.Warehouse.ErrorCord;
using B.S.Warehouse.Read.Api.Application.Command.AllocateCommand;
using MediatR;
using SqlSugar;

namespace B.S.Warehouse.Read.Api.Application.Handelr.AllocateHandler
{
    public class GetAllocateHandler : IRequestHandler<GetAllocateCommand, ApiResult<ApiPaging<Allocate>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public GetAllocateHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiResult<ApiPaging<Allocate>>> Handle(GetAllocateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<Allocate>> result = new ApiResult<ApiPaging<Allocate>>();
            var query = await db.Queryable<Allocate>().Where(x => !x.IsDel).ToListAsync();

            int totalCount = query.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            query = query.OrderByDescending(a => a.AllocateId).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            ApiPaging<Allocate> paging = new ApiPaging<Allocate>()
            {
                totalCount = totalCount,
                PageCount = PageCount,
                Result = query.ToList(),

            };

            result.Code = ApiEnum.显示成功;
            result.MAG = ApiEnum.显示成功.ToString();
            result.data = paging;
            return result;
        }
    }
}
